package com.leyou.order.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @package com.leyou.order.interceptors
 * @description: 用户信息拦截器，获取用户登入状态
 * @author: 许超越
 * @date 2019/7/12 9:49
 * @version: V1.0
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private static final String COOKIE_NAME = "LY_TOKEN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取token
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            //获取载荷
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            //将用户信息存当前线程中
            UserHolder.setUser(payload.getUserInfo());
            return true;
        } catch (UnsupportedEncodingException e) {
            log.error("【订单服务解析】用户信息失败！", e);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
